package com.tbit.uqbike.service.business.impl;

import cn.hutool.core.io.FileUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.object.pojo.Account;
import com.tbit.uqbike.object.pojo.AdvanceDepositQuery;
import com.tbit.uqbike.object.pojo.dto.*;
import com.tbit.uqbike.object.pojo.vo.AdvanceDepositDetailVO;
import com.tbit.uqbike.object.pojo.vo.AdvanceDepositTotalDetailVO;
import com.tbit.uqbike.object.pojo.vo.AdvanceDepositTotalIncomeVO;
import com.tbit.uqbike.object.pojo.vo.AdvanceDepositVO;
import com.tbit.common.entity.view.PageResult;
import com.tbit.uqbike.service.business.AccountDayStatService;
import com.tbit.uqbike.service.business.AdvanceDepositStatService;
import com.tbit.uqbike.webmanager.dao.capital.UserCapitalChangeDao;
import com.tbit.uqbike.webmanager.dao.core.AccountDao;
import com.tbit.uqbike.webmanager.dao.stat.AccountDayStatDao;
import com.tbit.uqbike.webmanager.util.BeanUtils;
import com.tbit.uqbike.webmanager.util.DateUtils;
import com.tbit.uqbike.webmanager.util.StringUtil;
import com.tbit.uqbike.webmanager.util.csv.CsvExportUtils;
import com.tbit.uqbike.webmanager.util.csv.entity.ExportHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 财务统计-预存款统计Service
 *
 * @AUTHOR: wei.xing
 * @DATE: 2022-11-16 08:49
 **/
@Service
public class AdvanceDepositStatServiceImpl implements AdvanceDepositStatService {

    @Autowired
    CsvExportUtils csvExportUtils;

    @Autowired
    AccountDayStatService accountDayStatService;
    @Autowired
    UserCapitalChangeDao changeDao;

    @Resource
    AccountDao accountDao;

    @Autowired
    AccountDayStatDao accountDayStatDao;


    @Override
    public Long getLastTime(List<Integer> accountIds) {
        return accountDayStatService.selectLatelyDataTime(accountIds);
    }

    @Override
    public AdvanceDepositTotalDetailVO getTotalDetail(StatDetailDTO dto) {
        return accountDayStatDao.getAdvanceDepositTotalDetail(
                DateUtils.toYYYYMMDDInt(dto.getStartTime()),
                DateUtils.toYYYYMMDDInt(dto.getEndTime()),
                StringUtil.getIntegerList(dto.getAccountIds()),
                dto.getBrandId());
    }

    @Override
    public PageResult<AdvanceDepositDetailVO> getDetailPage(StatDetailPageDTO dto) {
        PageHelper.startPage(dto.getPageNO(), dto.getRowCount());
        StatDetailDTO statDetailDTO = BeanUtils.copyProperties(dto, StatDetailDTO.class);
        List<AdvanceDepositDetailVO> list = getDetailList(statDetailDTO);
        PageInfo<AdvanceDepositDetailVO> pageInfo = new PageInfo<>(list);
        return new PageResult<>(dto.getPageNO(), dto.getRowCount(), pageInfo.getTotal(), pageInfo.getPages(), list);
    }

    private List<AdvanceDepositDetailVO> getDetailList(StatDetailDTO dto) {
        List<AdvanceDepositDetailVO> list = accountDayStatDao.getAdvanceDepositDetailList(
                DateUtils.toYYYYMMDDInt(dto.getStartTime()),
                DateUtils.toYYYYMMDDInt(dto.getEndTime()),
                StringUtil.getIntegerList(dto.getAccountIds()),
                dto.getBrandId());

        Map<Integer, String> accountMap = accountDao.getByAccountIds(StringUtil.getIntegerList(dto.getAccountIds()))
                .stream().collect(Collectors.toMap(Account::getAccountId, v -> v.getName()));
        list.forEach(v -> {
            v.setAccountName(Integer.valueOf(-1).equals(v.getAccountId()) ? "未知区域" : accountMap.get(v.getAccountId()));
        });
        return list;
    }

    @Override
    public String exportDetail(StatDetailDownloadDTO dto) {
        StatDetailDTO statDetailDTO = BeanUtils.copyProperties(dto, StatDetailDTO.class);
        List<AdvanceDepositDetailVO> result = getDetailList(statDetailDTO);
        //获取临时路径
        File tempFile = csvExportUtils.getTempFile();
        try {
            File file = csvExportUtils.exportCsv(AdvanceDepositDetailVO.class, tempFile, dto.getFileName(), result);
            String uploadFileName = UUID.randomUUID().toString().replaceAll("-", "");
            //压缩上传oss
            return csvExportUtils.uploadZip(tempFile, uploadFileName, file);
        } finally {
            //删除本地文件
            FileUtil.del(tempFile);
        }
    }

    @Override
    public AdvanceDepositTotalIncomeVO getTotalIncome(AdvanceDepositIncomeDTO dto) {

        AdvanceDepositQuery query = BeanUtils.copyProperties(dto, AdvanceDepositQuery.class);
        query.setAccountIds(StringUtil.getIntegerList(dto.getAccountIds()));
        //转换为数据库的时间类型
        query.setStartTime(dto.getStartTime().getTime());
        query.setEndTime(dto.getEndTime().getTime());

        return changeDao.getAdvanceDepositTotalIncome(query);
    }

    @Override
    public PageResult<AdvanceDepositVO> getIncomePage(AdvanceDepositIncomePageDTO pageDTO) {
        AdvanceDepositIncomeDTO dto = BeanUtils.copyProperties(pageDTO, AdvanceDepositIncomeDTO.class);
        PageHelper.startPage(pageDTO.getPageNO(), pageDTO.getRowCount());
        List<AdvanceDepositVO> list = getIncomeDetailList(dto);
        PageInfo<AdvanceDepositVO> pageInfo = new PageInfo(list);
        return new PageResult<>(pageDTO.getPageNO(), pageDTO.getRowCount(), pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }

    @Override
    public String exportIncome(AdvanceDepositIncomeDownloadDTO downloadDTO) {

        //获取临时路径
        File tempFile = csvExportUtils.getTempFile();
        try {
            File file = exportIncome(downloadDTO, tempFile);
            String uploadFileName = UUID.randomUUID().toString().replaceAll("-", "");
            //压缩上传oss
            return csvExportUtils.uploadZip(tempFile, uploadFileName, file);
        } finally {
            //删除本地文件
            FileUtil.del(tempFile);
        }
    }

    @Override
    public File exportIncome(AdvanceDepositIncomeDownloadDTO downloadDTO, File tempFile) {
        //自定义导出处理器
        ExportHandler exportHandler = baseEntity -> {
            AdvanceDepositIncomeDTO dto = BeanUtils.copyProperties(downloadDTO, AdvanceDepositIncomeDTO.class);
            //设置时间
            dto.setStartTime(baseEntity.getStartTime());
            dto.setEndTime(baseEntity.getEndTime());
            List<AdvanceDepositVO> list = getIncomeDetailList(dto);
            return list;
        };
        Date startTime = downloadDTO.getStartTime();
        Date endTime = downloadDTO.getEndTime();
        //多线程导出csv
        File file = csvExportUtils.exportBigCsv(exportHandler, AdvanceDepositVO.class, startTime, endTime, tempFile, downloadDTO.getFileName());
        return file;
    }

    private List<AdvanceDepositVO> getIncomeDetailList(AdvanceDepositIncomeDTO dto) {
        AdvanceDepositQuery query = BeanUtils.copyProperties(dto, AdvanceDepositQuery.class);
        query.setAccountIds(StringUtil.getIntegerList(dto.getAccountIds()));
        //转换为数据库的时间类型
        query.setStartTime(dto.getStartTime().getTime());
        query.setEndTime(dto.getEndTime().getTime());
        List<AdvanceDepositVO> list = changeDao.getAdvanceDepositList(query);
        //关联区域名称
        setAccountName(list);
        return list;
    }

    private void setAccountName(List<AdvanceDepositVO> list) {
        Map<Integer, Account> accountMap = new HashMap<>();
        if (!list.isEmpty()) {
            List<Integer> newAccountIds = list.stream().map(v -> v.getAccountId()).distinct().collect(Collectors.toList());
            List<Account> accountList = accountDao.getByAccountIds(newAccountIds);
            accountMap = accountList.stream().collect(Collectors.toMap(Account::getAccountId, v -> v));
            for (AdvanceDepositVO v : list) {
                Integer accountId = v.getAccountId();
                if (accountMap.get(accountId) != null) {
                    v.setAccountName(accountMap.get(accountId).getName());
                }
            }
        }
    }
}
